/*global window */

/* Date */
(function(){
	
	var fDate;
	
	function leadingZero(n) {
		return String("0"+n).substr(-2);
	}
	function parseRepeat(str, pos, chr) {
		var end = pos + 1;
		var length = str.length;
		while (end < length && str.charAt(end) === chr) {
			end++;
		}
		return end - pos;
	}
	function getMonth(m, cnt) {
		switch (cnt) {
			case 3: return fDate.monthAbbreviations[m];
			case 2: return leadingZero(m+1);
			case 1: return m+1;
			default: return fDate.monthNames[m];
		}
	}
	function getDay(d, cnt) {
		switch (cnt) {
			case 3: return fDate.weekDayNames[d.getUTCDay()].substr(0,3);
			case 2: return leadingZero(d.getUTCDate());
			case 1: return d.getUTCDate();
			default: return fDate.weekDayNames[d.getUTCDay()];
		}
	}
	function getHour(h, cnt) {
		switch (cnt) {
			case 3: return leadingZero(h);
			case 2: return leadingZero(h > 12 ? h-12 : h);
			case 1: return h > 12 ? h-12 : h;
			default: return leadingZero(h+1);
		}
	}
	function getDigit(d, cnt) {
		switch (cnt) {
			case 2: return leadingZero(d);
			default: return d;
		}
	}
	
	fDate = {
		format : function(date, formatStr) {
			var output = [];
			var inc = 0;
			for (var i = 0; i < formatStr.length; i += inc) {
				var chr = formatStr.charAt(i);
				switch (chr) {
					case 'M':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getMonth(date.getMonth(), inc));
						break;
					case 'D': case 'd':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getDay(date, inc));
						break;
					case 'Y': case 'y':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getDigit(date.getFullYear(), inc));
						break;
					case 'H': case 'h':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getHour(date.getHours(), inc));
						break;
					case 'N': case 'n': case 'm':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getDigit(date.getMinutes(), inc));
						break;
					case 'S': case 's':
						inc = parseRepeat(formatStr, i, chr);
						output.push(getDigit(date.getSeconds(), inc));
						break;
					case 'T': case 't':
						inc = parseRepeat(formatStr, i, chr);
						if (inc < 2) {
							output.push((date.getHours() > 11) ? "P" : "A");
						}
						else {
							output.push((date.getHours() > 11) ? "PM" : "AM");
						}
						break;
					case 'Z': case 'z':
						output.push("ET");
						break;
					default:
						output.push(chr);
						inc = 1;
						break;
				}
			}
			//console.log(output.join(''));
			return output.join('');
		},
		monthNames : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
		monthAbbreviations : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"],
		weekDayNames : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
	};
	window.fDate = fDate;
	
	
})();